<template>
  <a-spin :spinning="queryLoading">
    <div class="member-mng">
      <div v-for="key in Object.keys(computedData)" :key="key" class="role-item">
        <div class="label">{{ key }}：</div>
        <div class="tag-box">
          <template v-for="item in (computedData[key] as any)" :key="item.targetUser">
            <div class="tag-item">
              {{ item.userAttribute.userName }}
              <close-outlined
                class="tag-icon"
                @click="deleltePermission(item)"
                v-auth="[
                  {
                    objectId,
                    objectType,
                    role: Role.manager,
                  },
                  {
                    objectId: objectParentId,
                    objectType: ResourceType.app,
                    role: Role.manager,
                  },
                ]"
              />
            </div>
          </template>
        </div>
      </div>
      <a-button
        class="add-btn"
        @click="visible = true"
        v-auth="[
          {
            objectId,
            objectType,
            role: Role.manager,
          },
          {
            objectId: objectParentId,
            objectType: ResourceType.app,
            role: Role.manager,
          },
        ]"
      >
        <template #icon>
          <PlusOutlined />
        </template>
        添加
      </a-button>
    </div>
  </a-spin>
  <a-modal
    title="添加用户"
    :width="800"
    :visible="visible"
    @cancel="onClose"
    @ok="onOk"
    :confirmLoading="loading"
    destroy-on-close
    :maskClosable="false"
    centered
  >
    <SchemaForm />
  </a-modal>
</template>
<script setup lang="ts">
import { groupBy } from 'lodash';
import { Modal, message } from 'ant-design-vue';
import { PlusOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { FormSchema, useForm } from '../SchemaForm';
import { addPermission, queryPermission, delPermission } from '@/api/userAndAuth';
import { ResourceType, Role } from '@/enums/pipelineEnum';
import { usePermissionStore } from '@/store/modules/permission';

const props = defineProps({
  roleOptions: {
    type: Array<any>,
    default: [],
    required: true,
  },
  objectId: {
    type: String,
    default: '',
    required: true,
  },
  objectType: {
    type: String,
    defualt: '',
    required: true,
  },
  objectParentId: {
    type: String,
    default: '',
  },
});
const permissionStore = usePermissionStore();
const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      label: '用户',
      field: 'user',
      component: 'RichSelect',
      required: true,
      componentProps: {
        optionMode: 'api',
        labelInValue: true,
        api: '/devops/api/sys/user/findUserList',
        fieldNames: { value: 'id', label: 'realName' },
        placeholder: '请选择用户',
        showSearch: true,
        isBackendSearch: true,
        queryField: 'realName',
      },
      colProps: {
        span: 24,
      },
    },
    {
      label: '角色',
      field: 'role',
      component: 'Select',
      required: true,
      componentProps: {
        labelInValue: true,
        options: props.roleOptions,
      },
      colProps: {
        span: 24,
      },
    },
  ] as FormSchema[],
});
const visible = ref(false);
const loading = ref(false);
const queryLoading = ref(false);
const permissionData = ref([]);
const computedData = computed(() => {
  const groupArr = groupBy(permissionData.value, 'userAttribute.roleName');
  return groupArr;
});

const fetchPermission = async () => {
  queryLoading.value = true;
  try {
    const data = await queryPermission({ objectId: props.objectId, objectType: props.objectType || '' });
    permissionData.value = data.map((item: any) => ({ ...item, userAttribute: JSON.parse(item.userAttribute) }));
  } finally {
    queryLoading.value = false;
  }
};

watchEffect(async () => {
  await fetchPermission();
});

const onClose = () => {
  visible.value = false;
  formRef.resetFields();
};

const onOk = async () => {
  const data = await formRef.validate();
  const hasExist =
    permissionData.value.filter(
      (item: any) => item.targetUser === data.user.value && item.userAttribute.role === data.role.value,
    )?.length > 0;
  if (hasExist) {
    message.warn(`${data.user.label}已拥有${data.role.label}角色，请重新选择`);
    return;
  }
  try {
    loading.value = true;
    await addPermission({
      objectParentId: props.objectParentId,
      objectId: props.objectId,
      objectType: props.objectType || '',
      targetUser: data.user.value,
      userAttribute: JSON.stringify({ userName: data.user.label, role: data.role.value, roleName: data.role.label }),
    });
    message.success('添加用户成功');
    fetchPermission();
    permissionStore.fetchPermissionList();
    onClose();
  } finally {
    loading.value = false;
  }
};

const deleltePermission = (item: any) => {
  // 当删除的是管理员，且只剩下一个管理员是不允许删除
  if (
    item.userAttribute.role === Role.manager &&
    permissionData.value.filter((item: any) => item.userAttribute.role === Role.manager).length == 1
  ) {
    message.warn('只剩下一个管理员，不允许删除');
    return;
  }
  Modal.confirm({
    title: '提示',
    centered: true,
    content: `是否确认删除${item.userAttribute.userName}的${item.userAttribute.roleName}权限`,
    onOk: async () => {
      await delPermission({ objectId: item.objectId, objectType: item.objectType, targetUser: item.targetUser });
      fetchPermission();
      permissionStore.fetchPermissionList();
      message.success('删除成功');
    },
  });
};
defineExpose({
  permissionData: permissionData,
});
</script>
<style scoped lang="less">
.member-mng {
  .add-btn {
    margin-top: 20px;
    margin-left: 100px;
    border-color: #d8e8f8;
    color: #2590ff;
  }
  .role-item {
    display: flex;
    margin: 24px 0 0 0;
    .label {
      width: 100px;
      text-align: right;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.8);
    }
    .tag-box {
      display: flex;
      gap: 8px;
      .tag-item {
        display: flex;
        align-items: center;
        gap: 8px;
        height: 24px;
        border-radius: 4px;
        background: rgba(37, 144, 255, 0.05);
        padding: 0 8px;
        &:hover {
          background: rgba(230, 55, 28, 0.1);
          .tag-icon {
            color: #e6371c;
          }
        }
        .tag-icon {
          cursor: pointer;
          font-size: 14px;
          color: #6b84a5;
        }
      }
    }
  }
}
</style>
